import type { ChatUserInfo, Relationship, WsMessage } from "@/types"
import { ElMessage } from "element-plus";
import { type Ref } from "vue"
import { useLoginUserStore } from "@/stores/loginUser";
import type { ChatRecord } from "../types";
import listener from '@/listener'

export const handleNewApplication = (data:WsMessage | any,applicationList:Ref<any[]>) => {
    console.log(data);
    console.log(applicationList.value);
    applicationList.value.push({
        id:data.appId,
        friendName:data.applier
    })
    ElMessage({
        message:data.applier + '请求加您好友'
    })
}
export const handleFriendRelationshipEstablish = (data:WsMessage | any,friendList:Ref<Relationship[]>) => {
    const loginUser = useLoginUserStore()
    const currentUserName = loginUser.getUserName()
    const relationship = data.relationship
    friendList.value.push({
        id:relationship.id,
        friendName:relationship.userName == currentUserName ? relationship.friendName : relationship.userName
    })
}

export const handleNewMessageRecieve = (data:WsMessage | any,
                                        chatList:Ref<Array<ChatUserInfo>>,
                                        allChatRecords:Ref<Map<string,any>>) => {
        const record:ChatRecord = data.msg
       
        if(allChatRecords.value!.has(record.relationshipId)) {
            allChatRecords.value.get(record.relationshipId)?.records!.push(record)
        }else {
            const m = new Map<string,any>()
            m.set('records',[record])
            m.set('totalNumberOfRecords',0)
            allChatRecords.value.set(record.relationshipId,{
                records:[record],
                totalNumberOfRecords:0
            })
        }
        let OK = true
        for(let index = 0; index < chatList.value.length; index++) {
            if(chatList.value[index].id == record.relationshipId) {
                chatList.value[index].lastDate = record.date as string
                chatList.value[index].lastMessage = record.content.includes('<img ') ? '[图片]' : record.content
                OK = false
                break
            }
        }
        const loginUser = useLoginUserStore()
        const currentUserName = loginUser.getUserName()
        if(OK) {
            chatList.value.push({
                id:record.relationshipId,
                friendName:currentUserName == record.from ? record.to : record.from,
                lastDate:record.date as string,
                lastMessage:record.content.includes('<img ') ? '[图片]' : record.content
            })
        }
        // listener.emit('test')
}